﻿using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

namespace Klinkby.MicroBus
{
    /// <summary>
    /// Creates the bus channels from Xml
    /// </summary>
    public static class Factory
    {
        static ILog _log = LogManager.GetLogger(typeof(Factory));

        /// <summary>
        /// Create the bus channels from an XmlReader stream
        /// </summary>
        /// <param name="configuration">urn:schemas-kli-dk:microbus-configuration</param>
        /// <returns>An <see cref="IAsyncFilter"/> object that holds the bus channel objects</returns>
        public static IAsyncFilter Create(XmlReader configuration)
        {
            _log.Info("Creating from XmlReader");
            if (configuration.ReadState != ReadState.Interactive)
                configuration.MoveToContent();
            return Create((XElement)XElement.ReadFrom(configuration));
        }

        /// <summary>
        /// Creat the bus channels from an Xml string
        /// </summary>
        /// <param name="configuration">urn:schemas-kli-dk:microbus-configuration</param>
        /// <returns>An <see cref="IAsyncFilter"/> object that holds the bus channel objects</returns>
        public static IAsyncFilter Create(string configuration)
        {
            _log.Info("Creating from string");
            return Create(XElement.Parse(configuration));
        }

        private static IAsyncFilter Create(XElement configuration)
        {
            _log.Debug("Xml read, now deserializing");
            return AsyncFilter.FromXml(
                configuration,
                typeof(Factory));
        }
    }
}
